<template>
  <div>
    <page-search :searchFormConfig="searchFormConfig"></page-search>
    <page-content
      :contentTableConfig="contentTableConfig"
      pageName="role"
      @createBtnClick="handleCreateData"
      @editBtnClick="handleEditData"
    ></page-content>
    <page-model
      :modelConfig="modelConfig"
      ref="pageModelRef"
      pageName="role"
      :defaultInfo="defaultInfo"
      :otherInfo="otherInfo"
    >
      <div class="menu-tree">
        <el-tree
          ref="elTreeRef"
          :data="entireMenus"
          show-checkbox
          node-key="id"
          :props="{ children: 'children', label: 'name' }"
          @check="handleCheckChange"
        />
      </div>
    </page-model>
  </div>
</template>

<script lang="ts">
import { defineComponent, computed, ref, nextTick } from 'vue'
import PageContent from '@/ components/page-content'
import { contentTableConfig } from './config/content.config'

import PageSearch from '@/ components/page-search'
import { searchFormConfig } from '../role/config/search.config'

import PageModel from '@/ components/page-model'
import { modelConfig } from './config/model.config'

import { usePageModel } from '@/hooks/use-page-model'
import { useStore } from 'vuex'

import { mapMenuLeafKeys } from '@/utils/map-menus'
import { ElTree } from 'element-plus'

export default defineComponent({
  components: {
    PageContent,
    PageSearch,
    PageModel
  },
  setup() {
    //L3: 回调函数中拿到的item，并且赋值key到number数组中,直接拿到所有的id
    const elTreeRef = ref<InstanceType<typeof ElTree>>()
    const editCallback = (item: any) => {
      const leftKeys = mapMenuLeafKeys(item.menuList)
      //点击编辑按钮之后，回调函数执行，但是还未来得及绑定template重的elTree组件内，所以要下一帧则可以正常回显
      nextTick(() => {
        elTreeRef.value?.setCheckedKeys(leftKeys, false)
      })
    }
    const [pageModelRef, defaultInfo, handleCreateData, handleEditData] =
      usePageModel(undefined, editCallback)
    const store = useStore()
    const entireMenus = computed(() => store.state.entireMenu)
    const otherInfo = ref({})
    //@check事件绑定自定义函数可以获取到checkbox的数据,赋值给otherInfo
    //目的是搜集所有的数据保存在一个大的对象，然后发送请求保存到服务器
    const handleCheckChange = (data1: any, data2: any) => {
      const halfCheckedKeys = data2.halfCheckedKeys
      const checkedKeys = data2.checkedKeys
      const menuList = [...halfCheckedKeys, ...checkedKeys]
      otherInfo.value = { menuList }
    }
    return {
      contentTableConfig,
      searchFormConfig,
      modelConfig,
      pageModelRef,
      defaultInfo,
      handleCreateData,
      handleEditData,
      entireMenus,
      handleCheckChange,
      otherInfo,
      elTreeRef
    }
  }
})
</script>

<style scoped lang="less">
.menu-tree {
  margin-left: 20px;
}
</style>
